package cn.whit.blog.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import cn.whit.blog.domain.User;


public class PriviledgeFilter implements Filter {

	public PriviledgeFilter() {
	}

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest myReq = (HttpServletRequest) request;
		// 判断当前的session中是否存在已经登录成功的用户
		User user = (User) myReq.getSession().getAttribute("loginUser");
		//对于指定的公共请求地址，放行
		//用户注册，用户登录，找回密码
		String method = request.getParameter("method");
		StringBuffer requestURL = ((HttpServletRequest) request).getRequestURL();
		System.out.println("过滤器"+requestURL);
		System.out.println(method);
		//博客
		if(requestURL.toString().contains("/blog/TblogServlet")) {
			if(method.contains("index")) {
				chain.doFilter(request, response);
				return;
			}
			if(method.contains("show")) {
				chain.doFilter(request, response);
				return;
			}
			if(method.contains("addvote")) {
				chain.doFilter(request, response);
				return;
			}
		}
		//用户登录
		if(requestURL.toString().contains("/blog/UserServlet")) {
			if(method.contains("tologin")) {
				chain.doFilter(request, response);
				return;
			}
			if(method.contains("login")) {
				chain.doFilter(request, response);
				return;
			}
			if(method.contains("reguser") || method.contains("active") || method.contains("backpassword")) {
				chain.doFilter(request, response);
				return;
			}
		}
		
		//统计数据
		if(requestURL.toString().contains("/blog/StatisticalServlet")) {
			chain.doFilter(request, response);
			return;
		}
		
		//其它，需要登录
		if (null != user) {
			// 如果存在,放行
			chain.doFilter(request, response);
		} else {
			// 如果不存在,转入到提示页面
			myReq.setAttribute("message", "请先登录");
			// 转入到提示页面
			myReq.getRequestDispatcher("/view/user/login.jsp").forward(request, response);
		}

	}

	public void init(FilterConfig fConfig) throws ServletException {
	}

}
